#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <sys/time.h>
#include "../errno.h"
#include "../simconndata.h"

int simconndata_bufsize = 0;
unsigned char simconndata_buf[258];

int read_buf(int fd) {
	int count;

	if (!simconndata_bufsize) {
		if (read(fd, simconndata_buf, 1) == 1)
			simconndata_bufsize++;
		else
			return 1;
	}
	count = read(fd, simconndata_buf + simconndata_bufsize, simconndata_buf[0] - simconndata_bufsize);
	if (count > 0)
		simconndata_bufsize += count;
	if (simconndata_bufsize == simconndata_buf[0])
		return 0;
	return 1;
}

void read_data(int fd, void *data, int size) {
	int count;
	char *buf = (char *)data;

	while (size > 0) {
		count = read(fd, buf, size);
		if (count > 0) {
			buf += count;
			size -= count;
		}
	}
}

int read_pack(int fd, int *packid, void *pack, int size, int wait_second) {
	int elasped = 0;
	struct timeval start, end;

	gettimeofday(&start, 0);
	while (read_buf(fd) && wait_second > elasped) {
		usleep(10000);
		gettimeofday(&end, 0);
		elasped = 1000000 * ( end.tv_sec - start.tv_sec ) + end.tv_usec - start.tv_usec; 
		elasped /= 1000000;
	}
	if (simconndata_buf[0] != simconndata_bufsize)
		return -E_SIMULATOR_NOT_READY;
	*packid = simconndata_buf[1];
	memcpy(pack, simconndata_buf + 2, size > simconndata_bufsize - 2 ? simconndata_bufsize - 2 : size);
	simconndata_bufsize = 0;
	return 0;
}

int write_pack(int fd, int packid, void *pack, int size) {
	unsigned char tmp;

	tmp = size + 2;
	if (write(fd, &tmp, 1) < 0)
		return -E_PIPE_CLOSED;
	tmp = packid;
	if (write(fd, &tmp, 1) < 0)
		return -E_PIPE_CLOSED;
	if (write(fd, pack, size) < 0)
		return -E_PIPE_CLOSED;
	return 0;
}
